package com.central.scheduler.master.runner.task;

import com.central.common.enums.TaskType;
import com.central.common.model.TaskDefinition;
import com.central.common.properties.Property;
import com.central.scheduler.master.config.MasterConfig;
import com.central.scheduler.master.utils.SwitchTaskUtils;
import com.central.scheduler.service.bean.SpringApplicationContext;
import com.central.scheduler.common.enums.DependResult;
import com.central.scheduler.common.enums.ExecutionStatus;
import com.central.scheduler.common.task.switchtask.SwitchParameters;
import com.central.scheduler.common.task.switchtask.SwitchResultVo;
import com.central.scheduler.common.utils.JSONUtils;
import com.central.scheduler.common.utils.NetUtils;
import com.central.scheduler.dao.model.ProcessInstance;
import com.central.scheduler.dao.model.TaskInstance;
import com.central.scheduler.service.utils.LogUtils;
import org.apache.commons.lang.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author Tindy
 * @date 2021/12/20
 * @describe
 */
public class SwitchTaskProcessor extends BaseTaskProcessor {

    protected final String rgex = "['\"]*\\$\\{(.*?)\\}['\"]*";

    private TaskInstance taskInstance;

    private ProcessInstance processInstance;
    TaskDefinition taskDefinition;

    MasterConfig masterConfig = SpringApplicationContext.getBean(MasterConfig.class);

    /**
     * switch result
     */
    private DependResult conditionResult;

    @Override
    public boolean submit(TaskInstance taskInstance, ProcessInstance processInstance, int masterTaskCommitRetryTimes, int masterTaskCommitInterval) {

        this.processInstance = processInstance;
        this.taskInstance = processService.submitTask(taskInstance, masterTaskCommitRetryTimes, masterTaskCommitInterval);

        if (this.taskInstance == null) {
            return false;
        }
        taskDefinition = processService.findTaskDefinition(
                taskInstance.getTaskDefinitionId()
        );
        taskInstance.setLogPath(LogUtils.getTaskLogPath(processInstance.getProcessDefinitionCode(),
                processInstance.getProcessDefinitionVersion(),
                taskInstance.getProcessInstanceId(),
                taskInstance.getId()));
        taskInstance.setHost(NetUtils.getAddr(masterConfig.getListenPort()));
        taskInstance.setState(ExecutionStatus.RUNNING_EXECUTION);
        taskInstance.setStartTime(new Date());
        processService.updateTaskInstance(taskInstance);
        return true;
    }

    @Override
    public void run() {
        try {
            if (!this.taskState().typeIsFinished() && setSwitchResult()) {
                endTaskState();
            }
        } catch (Exception e) {
            logger.error("update work flow {} switch task {} state error:",
                    this.processInstance.getId(),
                    this.taskInstance.getId(),
                    e);
        }
    }

    @Override
    protected boolean pauseTask() {
        this.taskInstance.setState(ExecutionStatus.PAUSE);
        this.taskInstance.setEndTime(new Date());
        processService.saveTaskInstance(taskInstance);
        return true;
    }

    @Override
    protected boolean killTask() {
        this.taskInstance.setState(ExecutionStatus.KILL);
        this.taskInstance.setEndTime(new Date());
        processService.saveTaskInstance(taskInstance);
        return true;
    }

    @Override
    protected boolean taskTimeout() {
        return true;
    }

    @Override
    public String getType() {
        return TaskType.SWITCH.getDesc();
    }

    @Override
    public ExecutionStatus taskState() {
        return this.taskInstance.getState();
    }

    private boolean setSwitchResult() {
        List<TaskInstance> taskInstances = processService.findValidTaskListByProcessId(
                taskInstance.getProcessInstanceId()
        );
        Map<String, ExecutionStatus> completeTaskList = new HashMap<>();
        for (TaskInstance task : taskInstances) {
            completeTaskList.putIfAbsent(task.getName(), task.getState());
        }
        SwitchParameters switchParameters = (SwitchParameters) taskInstance.getRelationParameters();
        List<SwitchResultVo> switchResultVos = switchParameters.getDependTaskList();
        SwitchResultVo switchResultVo = new SwitchResultVo();
        switchResultVo.setNextNode(switchParameters.getNextNode());
        switchResultVos.add(switchResultVo);
        int finalConditionLocation = switchResultVos.size() - 1;
        int i = 0;
        conditionResult = DependResult.SUCCESS;
        for (SwitchResultVo info : switchResultVos) {
            logger.info("the {} execution ", (i + 1));
            logger.info("original condition sentence：{}", info.getCondition());
            if (StringUtils.isEmpty(info.getCondition())) {
                finalConditionLocation = i;
                break;
            }
            String content = setTaskParams(info.getCondition().replaceAll("'", "\""), rgex);
            logger.info("format condition sentence::{}", content);
            Boolean result = null;
            try {
                result = SwitchTaskUtils.evaluate(content);
            } catch (Exception e) {
                logger.info("error sentence : {}", content);
                conditionResult = DependResult.FAILED;
                break;
            }
            logger.info("condition result : {}", result);
            if (result) {
                finalConditionLocation = i;
                break;
            }
            i++;
        }
        switchParameters.setDependTaskList(switchResultVos);
        switchParameters.setResultConditionLocation(finalConditionLocation);
        taskInstance.setRelationParameters(switchParameters);
        taskInstance.setTaskContent(JSONUtils.toJsonString(switchParameters));

        logger.info("the switch task depend result : {}", conditionResult);
        return true;
    }

    /**
     * update task state
     */
    private void endTaskState() {
        ExecutionStatus status = (conditionResult == DependResult.SUCCESS) ? ExecutionStatus.SUCCESS : ExecutionStatus.FAILURE;
        taskInstance.setEndTime(new Date());
        taskInstance.setState(status);
        processService.updateTaskInstance(taskInstance);
    }

    public String setTaskParams(String content, String rgex) {
        Pattern pattern = Pattern.compile(rgex);
        Matcher m = pattern.matcher(content);
        Map<String, Property> globalParams = processInstance.getGlobalParams()
                .stream()
                .collect(Collectors.toMap(Property::getProp, Property -> Property));
        Map<String, Property> varParams = taskInstance.getVarPool()
                .stream()
                .collect(Collectors.toMap(Property::getProp, Property -> Property));
        if (varParams.size() > 0) {
            varParams.putAll(globalParams);
            globalParams = varParams;
        }
        while (m.find()) {
            String paramName = m.group(1);
            Property property = globalParams.get(paramName);
            if (property == null) {
                return "";
            }
            String value = property.getValue();
            if (!org.apache.commons.lang.math.NumberUtils.isNumber(value)) {
                value = "\"" + value + "\"";
            }
            logger.info("paramName：{}，paramValue{}", paramName, value);
            content = content.replace("${" + paramName + "}", value);
        }
        return content;
    }

}

